package com.pengpai.pangucms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pengpai.pangucms.DTO.CurrentUser;
import com.pengpai.pangucms.entity.SysPermission;
import com.pengpai.pangucms.entity.SysUser;
import com.pengpai.pangucms.mapper.SysPermissionMapper;
import com.pengpai.pangucms.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
@Transactional
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StrUtil.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名或密码为空！");
        }
        // 查询用户信息
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username).last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if(Objects.isNull(sysUser)){
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        //查询权限信息
        List<SysPermission> sysPermissionList = sysPermissionMapper.getSysPermissionListByUserId(sysUser.getUserId());
        Set<SimpleGrantedAuthority> grantedAuthorityList = new HashSet<>();
        if (sysPermissionList != null && sysPermissionList.size() > 0) {
            for (SysPermission sysPermission : sysPermissionList) {
                grantedAuthorityList.add(new SimpleGrantedAuthority(sysPermission.getPermissionKey()));
            }
        }

        CurrentUser currentUser = new CurrentUser();
        currentUser.setSysUser(sysUser);
        currentUser.setAuthorities(grantedAuthorityList);

        return currentUser;

    }
}
